package legumes.client.services.util.rpc;

import legumes.shared.domain.LegumesException;

import com.google.gwt.user.client.Window;

public abstract class SequencableRPCCall<T> extends AbstractAsyncHandler<T>
		implements Runnable {

	private RPCCallSequencer sequencer;

	public SequencableRPCCall() {
	}

	void setSequencer(RPCCallSequencer s_) {
		sequencer = s_;
	}

	/**
	 * Implements this method with your RPC call. The callback shall be "this".
	 */
	protected abstract void doCall();

	/**
	 * Call this method in {@link #onSuccess(Object)} method to call the next
	 * RPC call.
	 */
	protected void callNext() {
		sequencer.callNext();
	}

	@Override
	public void onSuccess(T result) {
		callNext();
	}

	@Override
	public void onFailure(Throwable caught_) {
		setThrowable(caught_);

		if (caught_ instanceof LegumesException) {
			callNext();
		} else {
			caught_.printStackTrace();
			Window.alert(caught_.getMessage());
		}
	}

	public void run() {
		doCall();
	}

}
